<template>
  <div>
    <!-- 搜索 -->
    <div class="hearder">
      <div class="form">
        <el-form :inline="true" :model="searchData" class="demo-form-inline" size="small">
          <el-form-item label="产品名称">
            <el-input v-model="searchData.productName" placeholder="产品名称"></el-input>
          </el-form-item>
          <el-form-item label="选择日期" size="small">
            <el-date-picker v-model="searchData.date" type="date" placeholder="选择日期" size="small"> </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmitSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="group">
        <el-row>
          <el-button type="warning" size="small" icon="el-icon-plus" @click="handleAdd">添加商品</el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteProductBatch">批量删除</el-button>
        </el-row>
      </div>
    </div>
    <!-- 展示 -->
    <div class="content">
      <el-table ref="multipleTable" tooltip-effect="dark" border header-row-class-name="active-header"
        :data="productList" :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="商品编号" width="100"></el-table-column>
        <el-table-column prop="productName" label="商品名称" width="180" show-overflow-tooltip> </el-table-column>
        <el-table-column prop="price" label="商品价格" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column prop="categoryName" label="商品类目" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="添加时间" width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ $dayjs(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="sellPoint" label="商品卖点" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="descs" label="商品描述" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ removeHTMLTag(scope.row.descs) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"> <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.$index, scope.row)">
              删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <Pagination :currentPage="currentPage" :productTotal="productTotal" :pageSize="pageSize"
      @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage"></Pagination>
  </div>
</template>

<script>
import Pagination from "@/components/pagination.vue";
import { getProducPagetList, deleteProductList } from "@/api/product.js";
import { removeHTMLTag, isValidDateTimeFormat } from "@/utils/common";
import { mapMutations } from 'vuex';
export default {
  data() {
    return {
      searchData: {
        productName: "",
        date: "",
      },
      productList: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      productTotal: 0,
      debounceTimeout: null, // debounce 的定时器变量,
      isSearch: false, //如果在搜索框内输入了内容，点击了查询按钮，那么此时在页面上的所有查询操作都要加上搜索条件
    };
  },
  created() {
    //初始化产品列表
    this.getProductPages();
  },
  methods: {
    ...mapMutations('productState', ['changeTitle','changeProductId']),
    removeHTMLTag,
    isValidDateTimeFormat,

    // 获取多选数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      //刷新产品列表
      this.triggerGetProductPageList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      //刷新产品列表
      this.triggerGetProductPageList();
    },
    onSubmitSearch() {
      this.isSearch = true;
      this.triggerGetProductPageList();
    },

    // 跳转添加产品页面
    handleAdd() {
      this.changeTitle('添加商品');
      this.changeProductId(0); //添加商品
      this.$router.push("/product/addProduct");
    },
    handleEdit(index, row) {
      // 修改全局状态的title
      this.changeTitle('编辑商品');
      this.changeProductId(row.id); //修改商品，要根据id获取数据
      this.$router.push({ path: '/product/editProduct' })
    },
    handleDelete(index, row) {
      const productIds = [row.id];
      this.deleteProductListByIds(productIds);
    },

    // 点击分页时，做了0.1秒的防抖
    triggerGetProductPageList(pageSizeReduceFlag) {
      if (this.debounceTimeout) {
        clearTimeout(this.debounceTimeout);
      }
      this.debounceTimeout = setTimeout(() => {
        this.getProductPages(pageSizeReduceFlag);
      }, 100);
    },

    // 删除多选数据
    deleteProductBatch() {
      if (this.multipleSelection.length == 0) {
        this.$message("未选中产品");
        return;
      }
      let productIds = [];
      // 获取多选productIds
      this.multipleSelection.forEach((product) => productIds.push(product.id));
      this.deleteProductListByIds(productIds);
    },
    deleteProductListByIds(productIds) {
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let pageSizeReduceFlag = false;
          if (this.multipleSelection.length == this.productList.length) {
            pageSizeReduceFlag = true;
          }
          deleteProductList(productIds)
            .then((res) => {
              const isDeleted = res.data;
              if (isDeleted) {
                this.triggerGetProductPageList(pageSizeReduceFlag);
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
              } else {
                this.$message({
                  type: "error",
                  message: "删除失败!",
                });
              }
            })
            .catch((error) => {
              this.$message({
                type: "error",
                message: error,
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 分页产品列表
    getProductPages(pageSizeReduceFlag) {
      if (pageSizeReduceFlag && this.currentPage != 1) {
        this.currentPage--;
      }
      let params2;
      if (this.isSearch) {
        if (this.searchData.date && !isValidDateTimeFormat(this.searchData.date)) {
          this.$message("时间格式错误！");
          return;
        }
        let dateFormatted = ""; // 默认值为空字符串
        if (this.searchData.date) {
          // 检查日期是否存在
          dateFormatted = this.$dayjs(this.searchData.date).format("YYYY-MM-DD HH:mm:ss");
        }
        params2 = { currentPage: this.currentPage, pageSize: this.pageSize, productName: this.searchData.productName, date: dateFormatted };
      } else {
        params2 = { currentPage: this.currentPage, pageSize: this.pageSize };
      }

      getProducPagetList(params2)
        .then((res) => {
          this.productTotal = res.data.productTotal;
          this.productList = res.data.productList;
        })
        .catch((error) => {
          this.$message(error);
        });
    },

  },
  components: { Pagination },
};
</script>

<style lang='less' scoped>
.hearder {
  background-color: white;
  padding: 10px;
}

.group {
  padding: 5px;
  border: 1px solid #f5f5ff;
}

.content {
  width: 100%;
  margin-top: 15px;

  ::v-deep .active-header {
    color: #333;
  }
}
</style>